package org.yxjme.ijkplayerlibrary.android;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.VideoView;
import com.bumptech.glide.Glide;
import org.yxjme.ijkplayerlibrary.R;
import java.util.Timer;
import java.util.TimerTask;

public class YXJControlVideoView extends FrameLayout implements YXJVideoListener{
    /**
     */
    private VideoView yxjVideoVIew;
    /**
     * 当前进度
     */
    private float currentProgress  ;
    /**
     * 上一次的进度
     */
    private float oldPosition ;

    private Handler handler ;
    /**
     * 记录seekBar 按下和抬起
     */
    private boolean isTrackingTouch = false ;
    /**
     * 是否需要支持底部控制导航
     *
     * 默认支持
     */
    private boolean isSupportBottomControl = true ;


    /**
     * 是否支持音频静音
     *
     */
    private boolean isSupportVocClose = false ;

    /**
     * 是否支持自動播放
     *
     */
    private boolean isSupportAutoPlay = false;


    /**
     * 是否支持音量和亮度控制
     */
    private boolean isSupportChangeVolumeAndLight = false ;




    /*****************bottom控制栏***************/
    /**
     * 记录是否正在显示
     */
    private boolean isShowBottom = true;
    /**
     * 5秒自动关闭
     */
    private int count = 5 ;
    /**
     * 动画执行时间
     */
    private int duration = 200;
    private Timer timer ;
    private TimerTask timerTask ;



    /**********************************/
    //暂位未图
    private ImageView placeHolder ;
    //加载动画
    private ProgressBar progressBar ;
    //视频中间的播放按钮
    private ImageView imCenterPlay ;


    /**********************************/
    private View bottomView ;
    private ImageView btn_play_video ;
    private TextView tv_current_time ;
    private TextView tv_total_time ;
    private SeekBar mSeekBar ;
    private FrameLayout contentView;

    /*音量布局*/
    private ChangeVolumeView changeVolumeView ;

    /*音量布局*/
    private ChangeLightView changeLightView ;

    private View.OnClickListener onClickListener;

    private View.OnLongClickListener onLongClickListener;

    public YXJControlVideoView setOnVideoClickListener(View.OnClickListener onClickListener){
        this.onClickListener=onClickListener;
        return YXJControlVideoView.this ;
    }


    public YXJControlVideoView setOnVideoLongClickListener(View.OnLongClickListener onLongClickListener){
        this.onLongClickListener=onLongClickListener;
        return YXJControlVideoView.this ;
    }


    public YXJControlVideoView isSupportBottomControl(boolean isSupportBottomControl) {
        this.isSupportBottomControl=isSupportBottomControl;
        if (!isSupportBottomControl){
            bottomView.setVisibility(GONE);
        }
        return this;
    }


    public YXJControlVideoView isSupportChangeVolumeAndLight(boolean isSupportChangeVolumeAndLight) {
        this.isSupportChangeVolumeAndLight=isSupportChangeVolumeAndLight;
        if (isSupportChangeVolumeAndLight){
            contentView.setOnTouchListener(new TouchListener(getContext(),contentView,changeLightView,changeVolumeView));
        }
        return this;
    }

    public YXJControlVideoView isSupportVocClose(boolean isSupportVocClose) {
        this.isSupportVocClose=isSupportVocClose;
        return this ;
    }


    public YXJControlVideoView isSupportAutoPlay(boolean isSupportAutoPlay) {
        this.isSupportAutoPlay=isSupportAutoPlay;
        return this;
    }

    /**
     * 添加暂无图
     *
     * @param url
     */
    public  YXJControlVideoView setPlaceHolder(String url) {
        if (!TextUtils.isEmpty(url)){
            Glide.with(getContext().getApplicationContext())
                    .load(url)
                    .into(placeHolder);
        }
        return this ;
    }




    /**
     * 添加暂无图
     *
     * @param bitmap
     */
    public <T> YXJControlVideoView setPlaceHolder(Bitmap bitmap) {
        if (bitmap!=null){
            placeHolder.setImageBitmap(bitmap);
        }
        return this ;
    }

    /**
     * @param yxjVideoVIew
     */
    public void setYxjVideoVIew(VideoView yxjVideoVIew) {
        this.yxjVideoVIew = yxjVideoVIew;
    }

    public YXJControlVideoView(@NonNull Context context) {
        this(context,null);
    }

    public YXJControlVideoView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public YXJControlVideoView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        /*父控件*/
        addContentView();
        /*添加暂无图*/
        addPlaceHolderView();
        /*加载动画view*/
        addLoadingView();
        /*底部控制栏*/
        addBottomView();
        /*中间播放按钮*/
        addCenterPlayView();
        /*添加音量view*/
        addVolumeView();
        /*添加亮度view*/
        addLightView();
    }


    private void addLightView() {
        changeLightView = new ChangeLightView(getContext());
        FrameLayout.LayoutParams f = new FrameLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        f.gravity = Gravity.TOP|Gravity.CENTER_HORIZONTAL ;
        contentView.addView(changeLightView,f);
        changeLightView.setVisibility(GONE);

        MarginLayoutParams marginLayoutParams= (MarginLayoutParams) changeLightView.getLayoutParams();
        marginLayoutParams.topMargin = 80 ;
    }


    private void addVolumeView() {
        changeVolumeView = new ChangeVolumeView(getContext());
        FrameLayout.LayoutParams f = new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        f.gravity = Gravity.TOP|Gravity.CENTER_HORIZONTAL ;
        contentView.addView(changeVolumeView,f);
        changeVolumeView.setVisibility(GONE);

        MarginLayoutParams marginLayoutParams= (MarginLayoutParams) changeVolumeView.getLayoutParams();
        marginLayoutParams.topMargin = 80 ;
    }




    /**
     * 中间播放控件
     *
     */
    private void addCenterPlayView() {
        imCenterPlay = new ImageView(getContext());
        imCenterPlay.setImageResource(R.drawable.icon_video_play);
        FrameLayout.LayoutParams f = new FrameLayout.LayoutParams(100, 100);
        f.gravity = Gravity.CENTER ;
        contentView.addView(imCenterPlay,f);
        imCenterPlay.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                start();
                imCenterPlay.setImageResource(R.drawable.icon_video_paus);
                dismissCenterPlay();
            }
        });
    }


    /**
     * 显示播放按钮
     */
    private void showCenterPlay(){
        imCenterPlay.setVisibility(VISIBLE);
        imCenterPlay.setEnabled(true);
        imCenterPlay.setAlpha(1f);
        imCenterPlay.setImageResource(R.drawable.icon_video_play);
    }



    /**
     * 关闭播放按钮
     */
    private void dismissCenterPlay(){
        imCenterPlay.setEnabled(false);
        imCenterPlay
                .animate()
                .setDuration(500)
                .alpha(0f)
                .setListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        super.onAnimationEnd(animation);
                        imCenterPlay.setAlpha(1f);
                        imCenterPlay.setVisibility(GONE);
                    }
                }).start();
    }


    private void addContentView() {
        contentView = new FrameLayout(getContext());
        contentView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showBottomViewAuto();
                if (onClickListener!=null){
                    onClickListener.onClick(v);
                }
            }
        });

        contentView.setOnLongClickListener(new OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (onLongClickListener!=null){
                    onLongClickListener.onLongClick(v);
                }
                return false;
            }
        });
        addView(contentView);
    }



    /**
     * 添加暂无图
     */
    private void addPlaceHolderView() {
        placeHolder = new ImageView(getContext());
        FrameLayout.LayoutParams f = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        f.gravity = Gravity.CENTER ;
        contentView.addView(placeHolder,f);
    }



    /**
     * 加载动画
     */
    private void addLoadingView() {
        progressBar = new ProgressBar(getContext());
        progressBar.setIndeterminateDrawable(getContext().getDrawable(R.drawable.loading));
        progressBar.setVisibility(GONE);
        FrameLayout.LayoutParams f = new FrameLayout.LayoutParams(70, 30);
        f.gravity = Gravity.CENTER ;
        contentView.addView(progressBar,f);
    }


    private ImageView btn_full_screen ;
    private boolean isFullScreen = false;
    private boolean isSupportFullScreen = false;

    public YXJControlVideoView isFullScreen(boolean isSupportFullScreen) {
       this. isSupportFullScreen =isSupportFullScreen ;
       if (isSupportFullScreen){
           btn_full_screen.setVisibility(VISIBLE);
       }else {
           btn_full_screen.setVisibility(GONE);
       }
        return this;
    }



    /**
     * 添加底部的 view
     */
    private void addBottomView(){
        bottomView = LayoutInflater.from(getContext()).inflate(R.layout.control_bottom_layout,contentView,false);
        tv_current_time = bottomView.findViewById(R.id.tv_current_time);
        tv_total_time = bottomView.findViewById(R.id.tv_total_time);
        mSeekBar = bottomView.findViewById(R.id.mSeekBar);
        mSeekBar.setOnSeekBarChangeListener(new VideoSeekListener());
        btn_play_video= bottomView.findViewById(R.id.btn_play_video);
        btn_play_video.setOnClickListener(new PlayAndPauseListener());
        btn_full_screen = bottomView.findViewById(R.id.btn_full_screen);
        btn_full_screen.setOnClickListener(new OnFullScreenListener());

        FrameLayout.LayoutParams f = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 100);
        f.gravity = Gravity.BOTTOM ;
        contentView.addView(bottomView,f);
    }







    /**
     * 显示底部控制栏
     */
    private void showBottomViewAuto(){
        stopTime();
        if (isSupportBottomControl){
            if (!isShowBottom){
                bottomView.setVisibility(VISIBLE);
                bottomView.animate()
                        .translationY(0)
                        .setDuration(duration)
                        .setListener(new AnimatorListenerAdapter() {
                            @Override
                            public void onAnimationEnd(Animator animation) {
                                super.onAnimationEnd(animation);
                                isShowBottom = true ;
                            }
                        }).start();
                startTime();
            }else {
                hintBottomView();
            }
        }
    }


    /**
     * 开始关闭bottom view 倒计时
     *
     */
    private void startTime(){
        count = 5;
        timer = new Timer();
        timer.schedule(timerTask = new TimerTask() {
            @Override
            public void run() {
                count -- ;
                if (isShowBottom && count < 0){
                    hintBottomView();
                }
            }
        },1000,1000);
    }


    /**
     * 停止时间
     *
     */
    private void stopTime(){
        if (timer!=null){
            timer.cancel();
            timer = null ;
        }

        if (timerTask!=null){
            timerTask.cancel();
            timerTask = null ;
        }
    }





    private void hintBottomView() {
        runOnMainUIThread(new Runnable() {
            @Override
            public void run() {
                if (isShowBottom){
                    bottomView.animate()
                            .translationY(bottomView.getMeasuredHeight())
                            .setDuration(duration)
                            .setListener(new AnimatorListenerAdapter() {
                                @Override
                                public void onAnimationEnd(Animator animation) {
                                    super.onAnimationEnd(animation);
                                    bottomView.setVisibility(GONE);
                                    isShowBottom = false ;
                                    stopTime();
                                }
                            }).start();
                }
            }
        });
    }


    public void runOnMainUIThread(Runnable runnable){
        Handler handler = new Handler(getContext().getMainLooper());
        handler.post(runnable) ;
    }


    /**
     * 关闭占位图
     */
    private void dismissPlaceHolder(){
        placeHolder.animate()
                .setDuration(500)
                .alpha(0)
                .setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                placeHolder.setVisibility(GONE);
                placeHolder.setAlpha(1f);
            }
        }).start();
    }







    /**
     * 开始播放
     */
    public void start(){
        if (yxjVideoVIew!=null&&!yxjVideoVIew.isPlaying()){
            yxjVideoVIew.start();
            sendTime();
            dismissCenterPlay();
            dismissPlaceHolder();

            btn_play_video.setImageResource(R.drawable.icon_video_paus);
            progressBar.setVisibility(VISIBLE);
        }else {
            pause();
        }
    }




    /**
     * 暂停
     *
     */
    public void pause(){
        if (yxjVideoVIew.isPlaying()&&yxjVideoVIew.isPlaying()){
            if (handler!=null){
                handler.removeCallbacks(runnable);
            }
            yxjVideoVIew.pause();
            btn_play_video.setImageResource(R.drawable.icon_video_play);
            progressBar.setVisibility(GONE);
            showCenterPlay();
        }
    }



    /**
     * 指定位置
     *
     * @param msec
     */
    public void seekTo(int msec){
        yxjVideoVIew.seekTo(msec);
        start();
        currentProgress = msec ;
        oldPosition = currentProgress;
    }


    /**
     * 重新获取焦点
     *
     */
    public void onResume(){
        placeHolder.setAlpha(1f);
        placeHolder.setVisibility(VISIBLE);
        showCenterPlay();

        if (isSupportVocClose){
            //静音
            VideoUtil.silentSwitchOn(getContext());
        }
    }



    /**
     *
     * 如果界面失去焦点调用此方法
     *
     */
    public void onPause(){
        pause();
        placeHolder.setVisibility(VISIBLE);
        //解除静音
        VideoUtil.silentSwitchOff(getContext());
    }



    /**
     * 销毁
     */
    public void destroy(){
        if (yxjVideoVIew != null && yxjVideoVIew.isPlaying()){
            yxjVideoVIew.stopPlayback();
            yxjVideoVIew = null ;
        }
        if (handler!=null){
            handler.removeCallbacks(runnable);
        }
    }




    @Override
    public void onPrepared(MediaPlayer mp) {

        totalTime(TimeUtil.stringForTime(mp.getDuration()));

        if (isSupportAutoPlay){
            start();
        }
    }


    @Override
    public void onInfo(MediaPlayer mp, int what, int extra) {

    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        btn_play_video.setImageResource(R.drawable.icon_video_play);
        progressBar.setVisibility(GONE);
        placeHolder.setVisibility(VISIBLE);
        yxjVideoVIew.seekTo(0);
        currentProgress = 0 ;

        currentProgress(0);
        /*当前时间*/
        playCurrentTime(0);

        showCenterPlay();
    }




    private class PlayAndPauseListener implements OnClickListener {

        @Override
        public void onClick(View v) {
            if (yxjVideoVIew!=null){
                start();
            }
        }
    }


    /**
     * 计时器
     */
    private void sendTime() {
        if (handler!=null){
            handler.removeCallbacks(runnable);
            handler = null ;
        }
        handler = new Handler();
        handler.postDelayed(runnable,200);
    }



    private Runnable runnable=new Runnable() {

        @Override
        public void run() {
            sendTime();
            if (yxjVideoVIew.isPlaying()){
                currentProgress = yxjVideoVIew.getCurrentPosition();
                /*当前进度*/
                currentProgress(currentProgress);
                /*当前时间*/
                playCurrentTime(currentProgress);
                /*表示是否在缓冲*/
                isBuffering();
            }
        }
    };



    /**
     * 是否加载中....
     *
     * @return
     */
    private boolean isBuffering() {
        boolean buffer = false ;
        if (currentProgress==oldPosition){
            /*表示正在缓冲加载*/
            buffer = true ;
            progressBar.setVisibility(VISIBLE);
        }else {
            /*正在播放了*/
            buffer = false ;
            progressBar.setVisibility(GONE);
            dismissPlaceHolder();
        }
        oldPosition  = currentProgress ;
        return buffer ;
    }


    /**
     * 播放总进度进度
     *
     * @return
     * @param time
     */
    private void totalTime(String time){
        tv_total_time.setText(time);
    }

    /**
     * 当前播放进度
     *
     * @return
     * @param currentProgress
     */
    private void playCurrentTime(float currentProgress){
        tv_current_time.setText( TimeUtil.stringForTime((int) currentProgress));
    }

    /**
     * 当前进度
     * @param currentProgress
     */
    private void currentProgress(float currentProgress){
        float scale= (float) ((currentProgress * 1.0) / yxjVideoVIew.getDuration());
        int progress = (int) (scale*100);
        mSeekBar.setProgress(progress);
    }


    private class VideoSeekListener implements SeekBar.OnSeekBarChangeListener {

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (isTrackingTouch){
                float scale= (float) (progress*1.0/100);
                float msec =  yxjVideoVIew.getDuration()*scale;
                yxjVideoVIew.seekTo((int) msec);
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            isTrackingTouch = true ;
            pause();
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            isTrackingTouch = false ;
            start();
        }
    }

    private class OnFullScreenListener implements OnClickListener {

        @Override
        public void onClick(View v) {
            if (!isFullScreen){
                isFullScreen =  true ;
                btn_full_screen.setImageResource(R.drawable.icon_cancel_full_screen);
            }else {
                isFullScreen = false ;
                btn_full_screen.setImageResource(R.drawable.icon_full_screen);
            }
            onFullScreen(isFullScreen);
        }
    }



    @Override
    public void onFullScreen(boolean b) {

    }

}
